﻿using Microsoft.Practices.Prism.PubSubEvents;
using Microsoft.Practices.Prism.StoreApps;
using Microsoft.Practices.Prism.StoreApps.Interfaces;
using System;
using System.Collections.Generic;
using System.Globalization;
using Windows.ApplicationModel.Activation;
using Windows.ApplicationModel.Background;
using WinRT.SIP.UI.BackgroundTasks;
using WinRT.SIP.UI.Common;
using WinRT.SIP.UILogic;
using WinRT.SIP.UILogic.Repositories;

namespace WinRT.SIP.UI
{
    /// <summary>
    /// Provides application-specific behavior to supplement the default Application class.
    /// </summary>
    sealed partial class App : MvvmAppBase
    {
        private readonly EventAggregator _eventAggregator = new EventAggregator();

        /// <summary>
        /// Initializes the singleton application object. This is the first line of authored code
        /// executed, and as such is the logical equivalent of main() or WinMain().
        /// </summary>
        public App()
        {
            this.InitializeComponent();
        }

        protected override void OnLaunchApplication(LaunchActivatedEventArgs args)
        {
            NavigationService.Navigate("Dialer", null);
        }

        protected override void OnInitialize(IActivatedEventArgs args)
        {
            base.OnInitialize(args);

            ServiceLocator.RegisterInstance<INavigationService>(NavigationService);
            ServiceLocator.RegisterInstance<IFlyoutService>(FlyoutService);
            ServiceLocator.RegisterInstance<IEventAggregator>(_eventAggregator);

            // Register Doubango Server
            var server = new DoubangoServer();
            server.Initialize();
            ServiceLocator.RegisterInstance<IDoubangoServer>(server);

            // Register repositories
            ServiceLocator.RegisterInstanceAsSingleton<ICallRepository, CallRepository>();
            ServiceLocator.RegisterInstanceAsSingleton<ICredentialsRepository, CredentialsRepository>();
            ServiceLocator.RegisterInstanceAsSingleton<INetworkSettingsRepository, NetworkSettingsRepository>();

            ViewModelLocator.SetDefaultViewTypeToViewModelTypeResolver((viewType) =>
            {
                string viewModelTypeName = string.Format(CultureInfo.InvariantCulture,
                    "WinRT.SIP.UILogic.ViewModels.{0}ViewModel, WinRT.SIP.UILogic, Version=1.0.0.0, Culture=neutral", viewType.Name);
                var viewModelType = Type.GetType(viewModelTypeName);
                return viewModelType;
            });

            RegisterBackgroundTasks();
        }

        protected override void OnLaunched(LaunchActivatedEventArgs args)
        {
            base.OnLaunched(args);
            if (NavigationService != null && !String.IsNullOrEmpty(args.Arguments))
            {
                ServiceLocator.Resolve<ICallRepository>().SetCurrentCallee(args.Arguments, true);
                NavigationService.Navigate("Call", null);
            }
        }

        private void RegisterBackgroundTasks()
        {
            if (!BackgroundTaskHelper.IsTaskRegistered("IncomingCallTask"))
            {
                BackgroundTaskHelper.RegisterBackgroundTask("WinRT.SIP.Tasks.IncomingCallTask", "IncomingCallTask",
                    new TimeTrigger(15, false),
                    new SystemCondition(SystemConditionType.InternetAvailable));
            }
        }

        protected override object Resolve(Type type)
        {
            // Use the container to resolve types (e.g. ViewModels and Flyouts) so their dependencies get injected.
            return ServiceLocator.Resolve(type);
        }

        protected override IList<SettingsCharmActionItem> GetSettingsCharmActionItems()
        {
            var settingsCharmItems = new List<SettingsCharmActionItem>();

            settingsCharmItems.Add(new SettingsCharmActionItem("Credentials", () => FlyoutService.ShowFlyout("Credentials")));
            settingsCharmItems.Add(new SettingsCharmActionItem("Network Settings", () => FlyoutService.ShowFlyout("NetworkSettings")));
            //settingsCharmItems.Add(new SettingsCharmActionItem("Credentials", () => NavigationService.Navigate("Credentials", null)));

            return settingsCharmItems;
        }
    }
}
